package kr.as3.samples.captureyourscreen
{
	import flash.desktop.Clipboard;
	import flash.desktop.ClipboardFormats;
	import flash.desktop.NativeDragManager;
	import flash.display.Bitmap;
	import flash.display.BitmapData;
	import flash.display.Sprite;
	import flash.events.Event;
	import flash.events.MouseEvent;
	import flash.filesystem.File;
	import flash.filesystem.FileMode;
	import flash.filesystem.FileStream;
	import flash.geom.Rectangle;
	import flash.utils.ByteArray;
	
	import kr.as3.utils.JPGEncoder;

	public class CaptureFrame extends Sprite
	{
		// Things on stage.
		public var dragArea: Sprite;
		public var area: Sprite;
		
		public function get bounds(): Rectangle
		{
			return this.area.getBounds( this );
		}
		
		public function CaptureFrame()
		{
			this.area.buttonMode = true;
			this.area.addEventListener( MouseEvent.MOUSE_DOWN, areaListener );
		}
		
		private function areaListener( e: MouseEvent ): void
		{
			this.dispatchEvent( new Event( "areaDown" ) );
			
			this.area.buttonMode = false;
			this.area.removeEventListener( MouseEvent.MOUSE_DOWN, areaListener );
		}
		
		public function addCapture( image: BitmapData ): void
		{
			this.area.addChild( new Bitmap( image ) );
			
			var file: File = new File( File.createTempFile().nativePath.split( "." )[ 0 ] + ".jpg" );
			
			var bytes: ByteArray = new JPGEncoder( 85 ).encode( image );
			
			var stream: FileStream = new FileStream();
			stream.open( file, FileMode.WRITE );
			stream.writeBytes( bytes );
			stream.close();
			
			var clipboard: Clipboard = new Clipboard();
			clipboard.setData( ClipboardFormats.FILE_LIST_FORMAT, [ file ] );
			
			NativeDragManager.doDrag( this, clipboard );
		}
	}
}